<template>
    <importDialog
      :dialogInfo="importDialogInfo"
      @baseMounted="baseMounted"
      :self="self">
    </importDialog>
</template>

<script>

import { ElMessageBox } from 'element-plus'
import { ref, unref, watch, onMounted } from 'vue'
import { post } from "/src/api/index";
import importDialog from '../import_dialog.vue'
import { ElMessage } from '/src/utils'
import { exportWorkspace } from '/src/utils'
import { init as sdp_workspace_config } from '../sdp_workspace_config/custom'
import { init as sdp_project } from '../sdp_project/custom'
import { init as sdp_template } from '../sdp_template/custom'
import { init as sdp_sql } from '../sdp_sql/custom'

export default {
    emits: ['baseMounted'],
    components:{
      importDialog,
    },
    props: {
      self:{},
    },
    setup(prop,context) {
      const importDialogInfo = ref({
          title: '导入',
          columns:[
            {
              prop: 'workspace_name',
              label:'工作区',
            },
          ],
          remote: {
            module: 'sdp_workspace',
            name: 'import_excel',
          },

          onInit: param => {
            const {mode, form, column, columns, get_remote_list, dialogInfo} = param

            Array.from([
              {
                prop: 'sdp_workspace_config',
                method: sdp_workspace_config,
              },
              {
                prop: 'sdp_project',
                method: sdp_project,
              },
              {
                prop: 'sdp_template',
                method: sdp_template,
              },
              {
                prop: 'sdp_sql',
                method: sdp_sql,
              }
            ]).forEach( ele => {
              prop.self[ele.prop] = unref({module: ref(ele.prop)})
              ele.method(prop.self[ele.prop])
            })
            
            dialogInfo.hideOri = dialogInfo.hide
            dialogInfo.onselectfile = (file => {
              if (file.name && file.name.indexOf('sdp_') == 0) {
                dialogInfo.form.workspace_name = file.name.replace('sdp_', '')
              } else {
                dialogInfo.form.workspace_name = file.name
              }
              dialogInfo.form.workspace_name = dialogInfo.form.workspace_name.split('.')[0]
              dialogInfo.form.tip_last = ''
              dialogInfo.form.tip = ''
            })
            dialogInfo.hide = (param) => {
              if (dialogInfo.form.tip && dialogInfo.form.tip.indexOf('已经取消') < 0 && dialogInfo.form.tip.indexOf('导入完成') < 0) {
                ElMessageBox.confirm('正在导入，是否要取消？', '警告', {
                  confirmButtonText: '确定',
                  cancelButtonText: '取消',
                  type: 'warning',
                })
                  .then(() => {
                    dialogInfo.list_index = -100
                  })
                  return;
              }
              dialogInfo.form.tip_last = ''
              dialogInfo.form.tip = ''
              return dialogInfo.hideOri(param)
            }
            dialogInfo.getKey = (item, workspaceName, tableName, keys) => {
              let key_ori = ''
              for(let key in keys) {
                key = keys[key]
                if (!item[key]) {
                  if (tableName == 'sdp_workspace' && key == 'name') {
                    key_ori+=key+'='+workspaceName+';'
                    continue;
                  } else if (tableName != 'sdp_workspace' && key == 'workspace_name') {
                    key_ori+=key+'='+workspaceName+';'
                    continue;
                  } else if (tableName == 'sdp_sql' && key == 'name' && item.parameter_catalog == 'sql') {
                    key_ori+=key+'='+';'
                    continue;
                  } else if (tableName == 'sdp_template' && key == 'name' && item.name === '') {
                    key_ori+=key+'='+';'
                    continue;
                  } else {
                    console.error('miss key:'+key+','+tableName,item)
                    key_ori+=key+'='+';'
                    continue;
                  }
                }
                key_ori+=key+'='+item[key]+';'
              }
              return key_ori
            },
            dialogInfo.fire = () => {
              if (dialogInfo.list_index < 0) {
                if (dialogInfo.form.tip_last) {
                  dialogInfo.form.tip = dialogInfo.form.tip_last
                }
                dialogInfo.form.tip += '\n已经取消'
                // self.$emit('fetch-data')
                dialogInfo.loading = false
                prop.self.handleSearch()
                return
              }
              if (dialogInfo.list_index == dialogInfo.list.length) {
                if (dialogInfo.form.tip_last) {
                  dialogInfo.form.tip = dialogInfo.form.tip_last
                }
                dialogInfo.form.tip += '\n导入完成'
                // self.$emit('fetch-data')
                dialogInfo.loading = false
                prop.self.handleSearch()
                return
              }
              let item = dialogInfo.list[dialogInfo.list_index]
              let method = item['_method']
              let tableName = item['_table_name']
              let count = item['_count']
              let msg = '正在导入' + tableName + ',共' + count + '条...'
              if (dialogInfo.form.tip.indexOf(msg) < 0) {
                if (dialogInfo.form.tip_last) {
                  dialogInfo.form.tip = dialogInfo.form.tip_last
                }
                dialogInfo.form.tip += '\n' + msg
                dialogInfo.form.tip_last = dialogInfo.form.tip
                dialogInfo.form.tip_index = 0
              } else {
                dialogInfo.form.tip_index++
                dialogInfo.form.tip = dialogInfo.form.tip_last + '\n已导入'+dialogInfo.form.tip_index+'条'
              }
              delete item['_method']
              delete item['_table_name']
              delete item['_count']
              post(method.split('/')[0], method.split('/')[1], item)
                .then((data) => {
                  dialogInfo.list_index++
                  setTimeout(dialogInfo.fire, 10)
                })
                .catch((err) => {
                  console.log('err', err)
                  console.log('item', item)
                  dialogInfo.loading = false
                  dialogInfo.form.tip += '\n错误：' + JSON.stringify(err)
                  dialogInfo.form.tip += '\n方法：' + method
                  dialogInfo.form.tip += '\n数据：' + JSON.stringify(item)
                  // dialogInfo.$emit('fetch-data')
                })
            },
            dialogInfo.onconfirm = (param) => {
              if (!form.workspace_name) {
                ElMessage.error(`请输入工作区名称`);
                return;
              }
              if (!form.file) {
                ElMessage.error(`请选择文件`);
                return;
              }
              post('sdp_workspace', 'list', {name: form.workspace_name})
              .then( data => {
                if (data && data.length) {
                  ElMessage.error(`工作区已经存在，请先删除后再重新导入：${form.workspace_name}`);
                  return;
                }
                let workspaceName_dest = form.workspace_name
                exportWorkspace({...prop.self, workspace_name: form.workspace_name, with_id:1})
                .then((datas_ori) => {
                  {
                    let file = form.file
                    var reader = new FileReader()
                    reader.readAsText(file)
                    reader.onload = function () {
                      form.tip = '正在分析:' + file.name
                      dialogInfo.loading = true
                      dialogInfo.count = 0

                      dialogInfo.last_error_data = undefined

                      let datas = JSON.parse(this.result)
                      dialogInfo.list = []
                      for (let workspaceName in datas) {
                        let data = [
                          { 'sdp_workspace/add': { table: 'sdp_workspace', keys: 'name' }},
                          { 'sdp_workspace_config/add': { table: 'sdp_workspace_config', keys: 'workspace_name,name'}},
                          { 'sdp_project/add': { table: 'sdp_project', keys: 'workspace_name,name' }},
                          { 'sdp_template/add': { table: 'sdp_template', keys: 'workspace_name, project_name,name,file_type,project,package_name' }},
                          { 'sdp_sql/add': { table: 'sdp_sql', keys: 'workspace_name,table_name, parameter_catalog,parameter_catalog_type,name' }},
                        ]
                        for (let dataItem in data) {
                          dataItem = data[dataItem]
                          for (let method in dataItem) {
                            let tableName = dataItem[method].table
                            let keys = dataItem[method].keys.split(',').map( item => item.trim())
                            let dataList = datas[workspaceName][tableName]
                            let dataList_ori_map = {}
                            if (datas_ori && datas_ori[tableName]) {
                              let dataList_ori = datas_ori[tableName]
                              for (let item in dataList_ori) {
                                item = {
                                  _method: method,
                                  _table_name: tableName,
                                  _count: dataList.length,
                                  ...dataList_ori[item],
                                }
                                let key_ori = dialogInfo.getKey(item, workspaceName_dest, tableName, keys)
                                if (key_ori) {
                                  dataList_ori_map[key_ori] = item
                                }
                              }
                            }
                            for (let item in dataList) {
                              item = {
                                _method: method,
                                _table_name: tableName,
                                _count: dataList.length,
                                ...dataList[item],
                              }
                              let key = dialogInfo.getKey(item, workspaceName_dest, tableName, keys)
                              let item_ori = ''
                              if (key) {
                                item_ori = dataList_ori_map[key]
                                item.sdp_key = key
                              }
                              delete item.id
                              if (item_ori) {
                                item.id = item_ori.id
                                item._method = method.replace('/add', '/update')
                                if (tableName == 'sdp_project' && item_ori.root_path && item_ori.root_path.indexOf('(root)') != 0) {
                                  delete item.root_path
                                } else if (tableName == 'sdp_workspace') {
                                  delete item.db_password
                                }
                              }
                              if ('sdp_sql/add' == method) {
                                item = { ...item, disable_auto_param: 1 }
                              }
                              if ('sdp_workspace/add' == method) {
                                item = { ...item, name: form.workspace_name }
                              } else {
                                item = {
                                  ...item,
                                  workspace_name: form.workspace_name,
                                }
                              }
                              let itemNamesObject = {
                                'sdp_template/add': ['file_template', 'remark'],
                                'sdp_sql/add': ['parameter_sql', 'java_imports', 'remarks'],
                              }
                              if (method in itemNamesObject) {
                                let itemNames = itemNamesObject[method]
                                itemNames.forEach((itemName) => {
                                  try {
                                    let lines = item[itemName]
                                    if (lines) {
                                      let destLines = ''
                                      lines.forEach((line) => {
                                        destLines += line + '\n'
                                      })
                                      item[itemName] = destLines
                                    }
                                  } catch (ex) {}
                                })
                              }
                              itemNamesObject = {
                                'sdp_template/add': ['extra_info'],
                                'sdp_sql/add': ['extra_info'],
                              }
                              if (method in itemNamesObject) {
                                let itemNames = itemNamesObject[method]
                                itemNames.forEach((itemName) => {
                                  try {
                                    if (item[itemName]) {
                                      item[itemName] = JSON.stringify(item[itemName], null, 2)
                                    }
                                  } catch (ex) {}
                                })
                              }
                              dialogInfo.list.push(item)
                            }
                          }
                        }
                      }
                      dialogInfo.list_index = 0
                      dialogInfo.form.tip_last = ''
                      dialogInfo.form.tip = ''
                      dialogInfo.fire(param)
                    }
                  }

                })
              })
            }
          },
        })

        const baseMounted = (v) => {
        }

        return {
          importDialogInfo,
          baseMounted,
        };
    },
};
</script>

<style scoped>
</style>
